package com.AAL.DAO;

import java.util.List;

import org.hibernate.classic.Session;

import com.AAL.DAO.Interface.IOrderDetailDAO;
import com.AAL.Model.Order;
import com.AAL.Model.OrderDetail;
import com.AAL.Utils.HibernateUtil;

public class OrderDetailDAO implements IOrderDetailDAO {

	@Override
	public OrderDetail saveAndUpdateOrderDetail(OrderDetail orderDetail) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(orderDetail);
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return orderDetail;
	}

	@Override
	public OrderDetail deleteOrderDetail(int orderDetailID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();
			OrderDetail orderDetail = (OrderDetail) session.load(
					OrderDetail.class, orderDetailID);
			if (null != orderDetail) {
				session.delete(orderDetail);
			}
			session.getTransaction().commit();
			return orderDetail;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		}
	}

	@Override
	public OrderDetail getOrderDetail(int orderDetailID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		OrderDetail orderDetail = (OrderDetail) session.load(OrderDetail.class,
				orderDetailID);
		return orderDetail;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrderDetail> getLstOrderDetailByOrder(Order order) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<OrderDetail> lstorderDetail = null;
		
		try{
			lstorderDetail = (List<OrderDetail>) session
					.createQuery(
							"from OrderDetail where order.orderID=:orderID")
					.setParameter("orderID",order.getOrderID()).list();
		}catch (Exception e) {
			return null;
		}
		
		return lstorderDetail;
	}
	
	//thu 5 ngay 31/3/2011
	//Huyen
	//

}
